//
//  CZPlaceholderTextView.m
//  发微博（表情键盘，照片选择器）
//
//  Created by WONG on 16/4/4.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "CZPlaceholderTextView.h"


/*
    自定义textView，里面有一个占位文本，当没有内容的时候会显示出来
 */
@interface CZPlaceholderTextView ()

@property (nonatomic,strong) UILabel *placeholderLabel;

@end

@implementation CZPlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer {
    if (self = [super initWithFrame:frame textContainer:textContainer]) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}
- (void)textDidChange {
    // hasText：是否有文本内容
    self.placeholderLabel.hidden = [self hasText];
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    
    _placeholderLabel.text = placeholder;
}


- (void)dealloc {
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - lazy load

- (UILabel *)placeholderLabel {
    if (!_placeholderLabel) {
        _placeholderLabel = [[UILabel alloc] init];
        
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        _placeholderLabel.font = self.font;
        
        [self addSubview:_placeholderLabel];
        
        // 添加约束, 独立的view.在其他工程也会使用的话,最好少依赖第三方框架
        _placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self addConstraint:[NSLayoutConstraint constraintWithItem:_placeholderLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:5]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:_placeholderLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:8]];
        [_placeholderLabel sizeToFit];
    }
    return _placeholderLabel;
}

@end







